﻿using Microsoft.OpenApi.Models;
using Microsoft.AspNetCore.Mvc;
using System.Reflection;
using S.Transplantation.Infrastructure.Imp;
using S.Transplantation.Infrastructure.InterFace;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using Authorization.Center.Jwt;

namespace S.Transplantation.Read.Api.Extensions
{
    public static class IOCServer
    {
        public static void AddJwtServer(this WebApplicationBuilder builder)
        {
            #region 配置授权校验规则

            //
            //var secretByte = Encoding.UTF8.GetBytes(builder.Configuration["JWTTokenOptions"]);
            JWTTokenOptions tokenOptions = new JWTTokenOptions();
            builder.Configuration.Bind("JWTToken", tokenOptions);
            builder.Services
                .AddAuthorization() //启用授权
                .AddAuthentication(JwtBearerDefaults.AuthenticationScheme) //指定授权的渠道
                 .AddJwtBearer(options =>  //这里是配置的鉴权的逻辑
                 {
                     //解开token以后，需要校验的相关信息
                     options.TokenValidationParameters = new TokenValidationParameters
                     {
                         //JWT有一些默认的属性，就是给鉴权时就可以筛选了
                         ValidateIssuer = true,//是否验证Issuer发布者
                         ValidateAudience = true,//是否验证Audience接受者
                         ValidateLifetime = true,//是否验证失效时间
                         ValidateIssuerSigningKey = true,//是否验证SecurityKey
                         ValidAudience = tokenOptions.Audience,//
                         ValidIssuer = tokenOptions.Issuer,//Issuer，这两项和前面签发jwt的设置一致
                         IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenOptions.SecurityKey)),
                         AudienceValidator = (m, n, z) =>
                         {
                             //这里可以写自己定义的验证逻辑
                             //return m != null && m.FirstOrDefault().Equals(builder.Configuration["audience"]);
                             return true;
                         },
                         LifetimeValidator = (notBefore, expires, securityToken, validationParameters) =>
                         {
                             //return notBefore <= DateTime.Now
                             //&& expires >= DateTime.Now;
                             ////&& validationParameters

                             return true;
                         }//自定义校验规则
                     };
                 });

            #endregion 配置授权校验规则
        }

        public static void AddRepositoryServer(this WebApplicationBuilder builder)
        {
            builder.Services.AddScoped<IDescendantTransfertRepository, DescendantTransfertRepository>();
        }

        public static void AddCorOption(this WebApplicationBuilder builder)
        {
            builder.Services.AddCors(options =>
            {
                options.AddPolicy("Transplantation"//请求名称
                    , policy =>
                    {
                        policy.SetIsOriginAllowed((host) => true)//基础跨域策略
                        .AllowAnyMethod()                       //容许所有请求方法
                        .AllowAnyHeader()                       //容许任何的头部来源
                        .AllowCredentials()                     //容许任何的请求证书
                        .WithExposedHeaders("Content-Disposition");//
                    });
            });
        }

        ///// <summary>
        ///// JWT
        ///// </summary>
        ///// <param name="collection"></param>
        ///// <param name="builder"></param>
        //public static void AddJWT(this IServiceCollection collection, WebApplicationBuilder builder)
        //{
        //    //jwt授权
        //    builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(a =>
        //    {
        //        //取出私钥
        //        var secretByte = Encoding.UTF8.GetBytes(builder.Configuration["Jwt:SecretKey"]);
        //        a.TokenValidationParameters = new TokenValidationParameters()
        //        {
        //            //验证发布者
        //            ValidateIssuer = true,
        //            ValidIssuer = builder.Configuration["Jwt:Issuer"],
        //            //验证接收者
        //            ValidateAudience = true,
        //            ValidAudience = builder.Configuration["Jwt:Audience"],
        //            //验证是否过期
        //            ValidateLifetime = true,
        //            //验证私钥
        //            IssuerSigningKey = new SymmetricSecurityKey(secretByte)
        //        };
        //    });
        //}
        public static void AddSwaggerOption(this WebApplicationBuilder builder)
        {
            #region swagger 配置

            //swagger添加报文头，方便做登录和退出：
            builder.Services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "转种服务(读)", Version = "v1" });
                //配置注释显示swagge ui当中
                var xmlfile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlpath = Path.Combine(AppContext.BaseDirectory, xmlfile);
                c.IncludeXmlComments(xmlpath, true);
                //Token绑定到configureServices
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    In = ParameterLocation.Header,//jwt默认存放Authorization信息的位置(请求头中)
                    Type = SecuritySchemeType.ApiKey,
                    Description = "直接在下框中输入Bearer {token}（注意两者之间是一个空格）",
                    Name = "Authorization",//jwt默认的参数名称
                    BearerFormat = "JWT",
                    Scheme = "Bearer"
                });
                c.AddSecurityRequirement(new OpenApiSecurityRequirement
        {
          {
            new OpenApiSecurityScheme
            {
              Reference=new OpenApiReference
              {
                Type=ReferenceType.SecurityScheme,
                Id="Bearer"
              }
            },
            new string[] {}
          }
        });
            });

            #endregion swagger 配置
        }
    }
}